import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    tokenInfo: JSON.parse(localStorage.getItem('token')) || {},
    userInfo: JSON.parse(localStorage.getItem('userInfo')) || {}
  },
  mutations: {
    // 设置mutation来更新userInfo
    mSetUserInfo (state, userObj) {
      // 1. 保存到vuex
      state.userInfo = userObj
      // 2. 做持久化 -- 保存到localstorage
      localStorage.setItem('userInfo', JSON.stringify(userObj))
    },
    // 设置mutation来更新userInfo中的头像信息
    mSetUserPhoto (state, photo) {
      // 1. 保存到vuex
      state.userInfo.photo = photo
      // 2. 做持久化 -- 保存到localstorage
      localStorage.setItem('userInfo', JSON.stringify(state.userInfo))
    },
    mSetToken (state, tokenObj) {
      // 持久化
      localStorage.setItem('token', JSON.stringify(tokenObj))
      // 修改vuex
      state.tokenInfo = tokenObj
    },
    mClearToken (state) {
      // 1. 保存到vuex
      state.tokenInfo = {}
      // 2. 做持久化 -- 保存到localstorage
      localStorage.removeItem('token')
    }
  }
})
